package com.welab.task3.controller;

import com.welab.task3.dto.request.UserDto;
import com.welab.task3.dto.response.Result;
import com.welab.task3.entity.User;
import com.welab.task3.service.UserService;
import com.welab.task3.util.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author dammein.yuan
 * @version v1.0
 * @Title: com.welab.task3.controller
 * @Description: 用户控制层实现
 * @Copyright: © 2020 ***
 * @Company: ***有限公司
 * @date 2020-3-9
 */
@RestController
@RequestMapping("user")
@Api(value = "用户接口", description = "用户相关接口")
public class UserController {

  @Autowired
  private UserService userService;

  /**
   * 删除用户
   *
   * @param id
   * @return com.welab.task3.dto.response.Result
   */
  @GetMapping("todelete/{id}")
  @ApiOperation(value = "用户删除接口", notes = "根据用户id删除用户记录")
  @ApiResponse(code = 200, message = "删除操作成功")
  public String todelete(@PathVariable("id") Integer id, HttpServletResponse response,
      Model model) {
    //代码实现
    Result result = userService.deleteByUserId(id);
    model.addAttribute("result", result);
    return response.encodeRedirectURL("/view");
  }

  /**
   * 退出登录，回到首页
   *
   * @param
   * @return index
   */
  @GetMapping("logout")
  @ApiOperation(value = "退出登录接口", notes = "退出登录,无须参数")
  @ApiResponse(code = 200, message = "退出成功")
  @ApiImplicitParam(name = "无须参数", value = "无须参数")
  public String logout(HttpSession session, HttpServletResponse response) {
    //代码实现
    session.removeAttribute("username");
    session.removeAttribute("usertype");
    return response.encodeRedirectURL("/index");
  }

  /**
   * 登录，跳转首页
   *
   * @param userDto
   * @return index
   */
  @PostMapping("tologin")
  @ApiOperation(value = "登录接口", notes = "登录")
  @ApiResponses({
      @ApiResponse(code = 0, message = "登录成功"),
      @ApiResponse(code = 99, message = "登录失败")
  })
  public String tologin(
      @RequestBody @ApiParam(name = "userDto", value = "用户对象（使用JSON格式）", required = true)
          UserDto userDto, HttpSession session, HttpServletResponse response, Model model) {
    //代码实现
    System.out.println(userDto);
    String name = userDto.getName();
    String password = MD5Util.md5(userDto.getPassword());
    Integer type = userDto.getType();

    Result result = userService.login(name, password, type);
    if (result.getCode() == 0) {
      session.setAttribute("username", name);
      session.setAttribute("usertype", type);
      model.addAttribute("result", result);
      return response.encodeRedirectURL("/index");
    }
    return response.encodeRedirectURL("/login");
  }

  /**
   * 注册，成功跳转首页，失败回到注册页
   * @param userDto
   * @return index/register
   */
  @PostMapping(value = "/toregister")
  @ApiOperation(value = "用户注册接口", notes = "用户注册")
  @ApiResponses({
      @ApiResponse(code = 0, message = "注册成功"),
      @ApiResponse(code = 99, message = "注册失败"),
      @ApiResponse(code = 500, message = "服务器内部错误")
  })
  public String toregister(
      @RequestBody @ApiParam(name = "userDto", value = "用户对象（使用JSON格式）", required = true)
          UserDto userDto, HttpServletResponse response, Model model) {
    System.out.println(userDto);
    String name = userDto.getName();
    String password = userDto.getPassword();
    Integer isdelete = userDto.getIsDelete();
    Integer type = userDto.getType();

    User user = new User();
    user.setName(name);
    user.setPassword(MD5Util.md5(password));
    user.setType(type);
    user.setGmtCreate(new Date());
    user.setGmtModified(new Date());
    user.setIsDelete(isdelete);
    Result result = userService.register(user);
    model.addAttribute("result", result);
      if (result.getCode() == 0) {
          return response.encodeRedirectURL("/index");
      } else {
          return response.encodeRedirectURL("/register");
      }
  }

  /**
   * 修改用户
   * @param userDto
   * @return modify/index
   */
  @PostMapping(value = "/tomodify")
  @ApiOperation(value = "修改用户信息接口", notes = "修改用户信息")
  @ApiResponses({
      @ApiResponse(code = 0, message = "修改成功"),
      @ApiResponse(code = 99, message = "修改失败"),
      @ApiResponse(code = 500, message = "服务器内部错误")
  })
  public String tomodify(@RequestBody @ApiParam(name = "userDto",value = "用户对象（使用JSON格式）", required = true)
      UserDto userDto , HttpSession session, HttpServletResponse response, Model model) {
    System.out.println(userDto);
    User user = new User();
    Integer id = userDto.getId();
    String name = userDto.getName();
    String password = MD5Util.md5(userDto.getPassword());
    Date gmt_create = userDto.getGmtCreate();
    Integer type = userDto.getType();
    Integer isdelete = userDto.getIsDelete();

    user.setId(id);
    user.setName(name);
    user.setPassword(password);
    user.setType(type);
    user.setGmtCreate(gmt_create);
    user.setGmtModified(new Date());
    user.setIsDelete(isdelete);
    Result result = userService.modified(user);
    model.addAttribute("result", result);
    //修改失败，重新回到修改页面
      if (result.getCode() == 0) {
          return response.encodeRedirectURL("/modify");
      }
    //修改成功，清除session，返回登录页面重新登录
    session.removeAttribute("username");
    session.removeAttribute("usertype");
    return response.encodeRedirectURL("/login");
  }

  /**
   * 查看用户列表
   * @param
   * @return view
   */
  @GetMapping(value = "/toview")
  @ApiOperation(value = "查看用户列表接口")
  @ApiResponses({
      @ApiResponse(code = 0, message = "查看成功"),
      @ApiResponse(code = 99, message = "查看失败"),
      @ApiResponse(code = 500, message = "服务器内部错误")
  })
  @ApiImplicitParam(name = "无须参数", value = "无须参数")
  public String toview(HttpServletResponse response, Model model) {
    List<User> list = userService.view();
    model.addAttribute("userlist", list);
    return response.encodeRedirectURL("/view");
  }

  /**
   * 添加用户
   *
   * @param userDto
   * @return adduser
   */
  @PostMapping(value = "/toadduser")
  @ApiOperation(value = "添加用户接口")
  @ApiResponses({
      @ApiResponse(code = 0, message = "添加成功"),
      @ApiResponse(code = 99, message = "添加失败"),
      @ApiResponse(code = 500, message = "服务器内部错误")
  })
  public String toadduser(@RequestBody @ApiParam(name = "userDto",value = "用户对象（使用JSON格式）", required = true)
      UserDto userDto, HttpServletResponse response, Model model) {
    User user = new User();
    System.out.println(userDto);
    String name = userDto.getName();
    String password = userDto.getPassword();

    user.setName(name);
    user.setPassword(MD5Util.md5(password));
    user.setType(2);
    user.setGmtCreate(new Date());
    user.setGmtModified(new Date());
    user.setIsDelete(0);
    Result result = userService.adduser(user);
    model.addAttribute("result", result);
      if (result.getCode() == 0) {
          return response.encodeRedirectURL("/adduser");
      }
    return response.encodeRedirectURL("/view");
  }
}
